package com.trex.lwlsh.dataDeal;

import com.trex.lwlsh.model.StepModel;
import com.trex.lwlsh.util.AssertUtil;
import com.trex.lwlsh.util.LogUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Create by Trex on 2018/1/16
 */
public class ParametersFactory {
    //存放参数变量值
    private static HashMap<String, String> daoMap=new  HashMap<String, String>();
    public HashMap<String, String> getDaoMap() {
        return daoMap;
    }
    public static void setDaoMap(String Key,String value) {
        daoMap.put(Key,value);
    }


    /**
     * 参数提取
     * @param step
     * @throws IOException
     */
    public  static void   GetParameter(StepModel step) throws IOException {
        String response=step.getResponse();
        String Parameter=step.getTransfer();
        if(Parameter!=null){
            String ParameterList[]=Parameter.split(",");
            for(int ium=0;ium<ParameterList.length;ium++){
                String Pstr=ParameterList[ium];
                if(Pstr.contains("=")){
                    AssertUtil jpath=new AssertUtil();
                    String key =Pstr.substring(0,Pstr.indexOf("="));
                    String value=Pstr.substring(Pstr.indexOf("=")+1,Pstr.length());
                    setDaoMap(key,jpath.JsonPath(response,value));
                }
            }
        }
        LogUtil.logs("参数池: " + daoMap.toString());
    }
    /**
     * 参数替换
     * @param
     * @throws IOException
     */
    public static  String   Extraction(String ArrStr) throws IOException {
        //Global Global = new Global();
        //替换传递参数
        if (ArrStr.contains("${")) {
            while (ArrStr.contains("${")) {
                String key = ArrStr.substring(ArrStr.indexOf("${") + 2, ArrStr.indexOf("}"));
                System.out.println(key+"----");
                if (daoMap.get(key.trim()) != null) {
                    ArrStr = ArrStr.replace("${" + key + "}", daoMap.get(key.trim()));
                    //判断url值是否有空格换行等
                    ArrStr =replaceStr(ArrStr);
                } else {
                    ArrStr = ArrStr.replace("${" + key + "}", "null");
                    //判断url值是否有空格换行等
                    ArrStr =replaceStr(ArrStr);
                }
            }

        }

        return ArrStr;
    }


    /**
     * 处理字符串格式
     * @param str
     * @return
     */
    public static String replaceStr(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
}
